<?php
class Pager{
	private $pageIndex;
	private $blockIndex;
	private $pagesPerBlock;
	private $itemsPerPages;
	private $totalItem;
	private $totalPage;
	private $totalBlock;
	private $hasFirst = false;
	private $hasLast = false;
	private $hasPrevious = false;
	private $hasNext= false;
	private $url;
	
	public function __construct($url,$pageIndex,$total,$itemsPerPages,$pagesPerBlock){
		$this->pageIndex = $pageIndex;
		$this->totalItem = $total;
		$this->itemsPerPages = $itemsPerPages;
		$this->pagesPerBlock = $pagesPerBlock;
	
		$this->totalPage = ceil($this->totalItem/$this->itemsPerPages);
		
		$this->totalBlock = ceil($this->totalPage/$this->pagesPerBlock);
		$this->blockIndex = ceil($this->pageIndex/$this->pagesPerBlock);
		
		if($this->blockIndex< $this->totalBlock){
			$this->hasLast = true;
			$this->hasNext = true;
		}
		if($this->blockIndex> 1){
			$this->hasFirst = true;
			$this->hasPrevious = true;
			
		}
		$this->url = $url;
		
		
	}
	public function getPages(){
	
		if(strpos($this->url,"?") === false){
			$this->url .="?page=";
			
		}else{
			
			$this->url.="&page=";
		}
		
		$pages = "<div id='pager'>";
		if($this->hasFirst){
		
				$pages .="<a href='".$this->url."1'>Đầu</a>";
		}
		
		
		if($this->hasPrevious){
			$previous = ($this->blockIndex-1)*$this->pagesPerBlock;
			$pages.="<a href='".$this->url.$previous."'>Trước</a>";
		}
		$pageStart = ($this->blockIndex-1)*$this->pagesPerBlock +1;
		$pageEnd = $pageStart + $this->pagesPerBlock -1;
		if($pageEnd > $this->totalPage){
			$pageEnd = $this->totalPage;
		}
		for($i = $pageStart;$i<=$pageEnd;$i++){
			if($i == $this->pageIndex){
				$pages .="<a class='current' href='".$this->url.$i."'>".$i."</a>";
			}else{
				$pages .="<a href='".$this->url.$i."'>".$i."</a>";
			}
		}
		if($this->hasNext){
			$next = $this->blockIndex*$this->pagesPerBlock +1;
			$pages.="<a href='".$this->url.$next."'>Sau</a>";
		}
		if($this->hasLast){
		
				$pages .="<a href='".$this->url.$this->totalPage."'>Cuối</a>";
		}
		
		$pages.="</div>";	
		return $pages;
	
	}
}